const fs = require('fs');
const request = require('superagent');
const progress = require('progress-stream');

const logger = require('./utils/logger');
const coloredChalk = require('./utils/coloredChalk');

const downloadVideos = (videoList, targetFolderPath) => {
    let count = 0;

    const streamToPromise = video => new Promise((resolve, reject) => {
        if (!video.contentURL) {
            logger(`Fail: ${video.title} 没有抓到contentURL`);
            resolve(false);
        } else {
            const filename = `${video.title}.mp4`;
            const filePath = `${targetFolderPath}/${filename}`;
            let fileSize;

            const fileStream = fs.createWriteStream(filePath)
                            .on('pipe', () => {
                                console.log('file write started');
                            })
                            .on('finish', () => {
                                logger(`Success: ${++count} ${video.title}`);
                                resolve(true);
                            })
                            .on('error', reject);


            request.get(video.contentURL)
                .on('response', (res) => {
                    fileSize = parseInt(res.headers['content-length'], 10);
                })
                .pipe(progress({
                    time: 5000,
                }).on('progress', (data) => {
                    const { transferred } = data;
                    const percentage = (transferred / fileSize) * 100;
                    const percentageStr = `${percentage.toFixed(2)}% transferred`;

                    console.log(`${video.title} \n=> %s`, coloredChalk(percentage, percentageStr));
                }))
                .pipe(fileStream);
        }
    });

    return Promise.all(videoList.map(streamToPromise));
};

// const path = require('path');
// const videoArr = [{
//     title: 'intro',
//     contentURL: 'https://udemy-assets-on-demand.udemy.com/2015-12-23_21-57-21-4c75e2e787a4b148fd10d214f09d31af/WebHD_720p.mp4?nva=20170530131235&token=0dff42c265688d4e3803c',
// }, {
//     title: 'purpose',
//     contentURL: 'https://udemy-assets-on-demand.udemy.com/2015-12-23_21-59-51-121e6f837f7577324ee69ea1c0bb8194/WebHD_720p.mp4?nva=20170530143012&token=0ed7adec34fbe8c38c4c2',
// }];
//
// downloadVideos(videoArr, path.resolve(__dirname, '../download'));

module.exports = downloadVideos
;
